package com.example.cloud_disk.service.impl;


import cn.mybatis.mp.core.mybatis.mapper.context.Pager;
import cn.mybatis.mp.core.sql.executor.chain.QueryChain;
import com.example.cloud_disk.constant.StatusConstant;
import com.example.cloud_disk.dto.AdminPermissionsDTO;
import com.example.cloud_disk.dto.AdminUserDTO;
import com.example.cloud_disk.dto.GetAdminUsersPageDTO;
import com.example.cloud_disk.dto.PutPassword;
import com.example.cloud_disk.entity.AdminUsers;
import com.example.cloud_disk.mapper.AdminUsersMapper;
import com.example.cloud_disk.service.AdminUserService;
import com.example.cloud_disk.utils.JwtUtil;
import com.example.cloud_disk.utils.Md5Util;
import com.example.cloud_disk.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author majun
 * @package com.example.cloud_disk.service.impl
 * @date 2024/10/21 20:33
 */

@Slf4j
@Service
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUsersMapper adminUsersMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 管理员登录
     *
     * @param adminUserDTO
     * @return
     */
    public String AdminLogin(AdminUserDTO adminUserDTO) {

        //查询管理员账户
        AdminUsers adminUsers = adminUsersMapper.get(where -> {
            where.eq(AdminUsers::getUsername, adminUserDTO.getUsername());
        });

        if (adminUsers.getStatus().equals(StatusConstant.DISABLE)) {

            //账户被禁用
            return "账户已被禁用，请联系管理员";

        }

        if (adminUsers == null) {
            //账户不存在
            return "账户不存在";

        }

        //账户存在，校验密码
        if (adminUsers.getPassword().equals(Md5Util.getMD5String(adminUserDTO.getPassword()))) {

            //账户密码正确，返回token
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", adminUsers.getId());
            claims.put("username", adminUserDTO.getUsername());
            String token = JwtUtil.genToken(claims);

            //将token存如redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 12, TimeUnit.HOURS);

            return token;

        }

        //账户密码不正确
        return "密码不正确";

    }

    /**
     * 管理员账号创建
     *
     * @param adminUserDTO
     * @return
     */
    public String SaveAdminUser(AdminUserDTO adminUserDTO) {

        //获取当前管理员用户id和username
        Map<String, Object> map = ThreadLocalUtil.get();

        //查询当前用户
        AdminUsers adminUsers = adminUsersMapper.get(where -> {
            where.eq(AdminUsers::getUsername, map.get("username"));
        });

        //判断管理是否用权限创建用户
        if (adminUsers.getCanDeleteAdmin().equals(StatusConstant.ENABLE)) {

            //有权限
            AdminUsers adminUsers1 = new AdminUsers();

            BeanUtils.copyProperties(adminUserDTO, adminUsers1);

            //加密密码
            adminUsers1.setPassword(Md5Util.getMD5String(adminUserDTO.getPassword()));

            //新用户取消所有权限
            adminUsers1.setCanDeleteUser(StatusConstant.DISABLE);
            adminUsers1.setCanDisableUser(StatusConstant.DISABLE);
            adminUsers1.setCanDeleteAdmin(StatusConstant.DISABLE);
            adminUsers1.setCanChangeStatus(StatusConstant.DISABLE);
            adminUsers1.setStatus(StatusConstant.ENABLE);

            //添加数据库
            adminUsersMapper.save(adminUsers1);

            return "管理员账户创建成功";

        }

        //无权限
        return "账户权限不足";

    }

    /**
     * 管理员权限修改
     *
     * @param adminPermissionsDTO
     * @return
     */
    public String ModificationPermissions(AdminPermissionsDTO adminPermissionsDTO) {

        Map<String, Object> map = ThreadLocalUtil.get();

        if (!Objects.equals(map.get("id").toString(), "1")) {

            return "账户权限不足";

        }

        adminUsersMapper.update(adminPermissionsDTO);

        return "权限修改成功";

    }

    /**
     * 修改管理员账户状态
     *
     * @param id
     * @return
     */
    public String upDataAdminStatus(Integer id) {

        Map<String, Object> map = ThreadLocalUtil.get();

        Integer AdminId = (Integer) map.get("id");

        AdminUsers adminUsers = QueryChain.of(adminUsersMapper)
                .eq(AdminUsers::getId, AdminId)
                .get();

        if (adminUsers.getCanChangeStatus().equals(StatusConstant.DISABLE)) {

            return "账户权限不足";

        }

        AdminUsers adminUsers1 = adminUsersMapper.get(where -> {
            where.eq(AdminUsers::getId, id);
        });

        // 切换管理员状态
        Integer newStatus = adminUsers1.getStatus() == StatusConstant.ENABLE ? StatusConstant.DISABLE : StatusConstant.ENABLE;

        adminUsers1.setStatus(newStatus);

        adminUsersMapper.update(adminUsers1);

        return "状态修改成功";

    }

    /**
     * 管理员账户分页及模糊查询
     *
     * @param getAdminUsersPageDTO
     * @return
     */
    public Pager<AdminUsers> getAdminUsersPage(GetAdminUsersPageDTO getAdminUsersPageDTO) {

        return QueryChain.of(adminUsersMapper)
                // 忽略 null 条件参数
                .ignoreNullValueInCondition(true)
                // 忽略 空字符串 条件参数
                .ignoreEmptyInCondition(true)
                .like(AdminUsers::getUsername, getAdminUsersPageDTO.getUsername())
                .paging(Pager.of(getAdminUsersPageDTO.getPageNumber(), getAdminUsersPageDTO.getPageSize()));

    }

    /**
     * 管理员账户删除
     *
     * @param id
     * @return
     */
    public String deleteAdminUser(Integer id) {

        Map<String, Object> map = ThreadLocalUtil.get();

        AdminUsers adminUsers = adminUsersMapper.get(where -> {
            where.eq(AdminUsers::getId, map.get("id").toString());
        });

        if (adminUsers.getCanDeleteAdmin().equals(StatusConstant.DISABLE)) {

            return "账户权限不足";

        } else {

            adminUsersMapper.delete(where -> {
                where.eq(AdminUsers::getId, id);
            });

            return "删除成功";

        }

    }

    /**
     * 修改管理员账户密码
     *
     * @param putPassword
     * @param token
     * @return
     */
    public String putAdminUserPassword(PutPassword putPassword, String token) {

        Map<String, Object> map = ThreadLocalUtil.get();

        AdminUsers adminUsers = adminUsersMapper.get(where -> {
            where.eq(AdminUsers::getId, map.get("id").toString());
        });

        if (!adminUsers.getPassword().equals(Md5Util.getMD5String(putPassword.getOldPassword()))) {
            return "密码错误请联系管理员";
        }

        if (!putPassword.getNewPassword().equals(putPassword.getConfirmPassword())) {
            return "两次密码不一致";
        }

        adminUsers.setPassword(Md5Util.getMD5String(putPassword.getNewPassword()));

        adminUsersMapper.update(adminUsers);

        stringRedisTemplate.delete(token);

        return "密码修改成功";
    }

}
